package com.lazyboyl.sharding.proxy.net.frontend;

import com.lazyboyl.sharding.proxy.config.ErrorCode;
import com.lazyboyl.sharding.proxy.net.proto.MySQLPacket;
import com.lazyboyl.sharding.proxy.net.proto.mysql.BinaryPacket;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author linzef
 * @since 2021-06-29
 * 类描述： 登陆成功以后执行的所有的sql命令的入口类
 */
public class FrontendCommandHandler extends ChannelHandlerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(ChannelHandlerAdapter.class);

    private FrontendConnection connection;

    public FrontendCommandHandler(FrontendConnection connection) {
        this.connection = connection;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        BinaryPacket bin = (BinaryPacket) msg;
        byte type = bin.data[0];
        switch (type) {
            case MySQLPacket.COM_INIT_DB:
                // just init the frontend
                connection.initDB(bin);
                break;
            case MySQLPacket.COM_QUERY:
                connection.query(bin);
                break;
            case MySQLPacket.COM_PING:
                connection.ping();
                break;
            case MySQLPacket.COM_QUIT:
                connection.close();
                break;
            default:
                connection.writeErrMessage(ErrorCode.ER_UNKNOWN_COM_ERROR, "Unknown command");
                break;
        }
    }
}
